package com.wangzhixuan.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.utils.ImageTools;
import com.wangzhixuan.commons.utils.PageInfo;
import com.wangzhixuan.commons.utils.PictureNarrowUtil;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.model.CArchivesImage;
import com.wangzhixuan.model.CusGroupImage;
import com.wangzhixuan.model.Customer;
import com.wangzhixuan.model.EleRate;
import com.wangzhixuan.model.EleSpec;
import com.wangzhixuan.model.Skydrive;
import com.wangzhixuan.model.vo.CArchivesImageVo;
import com.wangzhixuan.service.ICArchivesImageService;
import com.wangzhixuan.service.ICusGroupImageService;
import com.wangzhixuan.service.ICusGroupService;
import com.wangzhixuan.service.ICusImageService;
import com.wangzhixuan.service.ICustomerService;
import com.wangzhixuan.service.IEleRateService;
import com.wangzhixuan.service.IEleSpecService;
import com.wangzhixuan.service.IMeteringService;
import com.wangzhixuan.service.IOperationService;

/**
 * <p>
 *   前端控制器
 * </p>
 * @author zhixuan.wang
 * @since 2017-09-26
 */
@Controller
@RequestMapping("/customer")
public class CustomerController extends BaseController {
    
    @Autowired private ICustomerService customerService;
    
    @Autowired private IEleSpecService eleSpecService;
    
    @Autowired private IEleRateService eleRateService;
    
    @Autowired private IMeteringService meteringService;
    
    @Autowired private IOperationService operationService;
    
    @Autowired private ICusImageService cusImageService;
    
    @Autowired private ICusGroupService cusGroupService;
    
    @Autowired private ICusGroupImageService cusGroupImageService;
    
    @Autowired private ICArchivesImageService cArchivesImageService;
    
    @RequestMapping("/manager")
    public String manager() {
        return "customer/customerList";
    }


    @RequestMapping("/dataGrid")
    @ResponseBody
    public PageInfo dataGrid(Customer customer, Integer page, Integer rows, String sort,String order) {       
        PageInfo pageInfo = new PageInfo(page, rows, sort, order);
        Map<String, Object> condition = new HashMap<String, Object>();
        pageInfo.setCondition(condition);
        customerService.selectDataGrid(pageInfo);
        return pageInfo;
    }
    
    /**
     * excel页面
     * @param id
     * @return
     */
    @RequestMapping("/uploadExcelPage")
    public String uploadExcelPage() {
     return "customer/customerExcel";
    }
    
    /**
     * excel导入
     * @param id
     * @return
     * @throws Exception 
     * @throws IOException 
     */
    @RequestMapping("/uploadExcel")
    @ResponseBody
    public Object uploadExcelPage(Integer pId,@RequestParam("excel") MultipartFile excel
    		,HttpServletRequest request, HttpServletResponse response) throws IOException, Exception{
    	if(excel.isEmpty()){
    		 return renderError("请选择文件！");
    	}
    	String fileSuffixName = excel.getOriginalFilename().substring(          //获得后缀名
    			excel.getOriginalFilename().lastIndexOf("."));
    	Long a = getUserId();
    	long b = a;
    	int c = (int)b;
    	Integer id = c;
    /*	if(!(".xls".equals(fileSuffixName)&&".xlsx".equals(fileSuffixName))){
    		return renderError("请选择Excel文件！");
    	}*/
    	String name = excel.getOriginalFilename();
    	 String rootPath = getRootPath();
    	customerService.uploadExcel(name, excel,id,rootPath);
		return  renderSuccess("添加成功！");   
    }
    
    /**
     * 查看档案图片
     * @return
     */
    @RequestMapping("/archives")
    public Object archives(Integer cId,Model model) throws IOException, Exception{
    	if(cId == null){
    		 return renderError("重新选择！");
    	}
    	List<CArchivesImageVo> list = cArchivesImageService.findArchivesImage(cId);
    	model.addAttribute("listPicture", list);
		return  "customer/customerArchives";  
    }
    
    
    /**
     * 查看运维图片
     * @return
     */
    @RequestMapping("/picture")
    public Object picture(Integer cId,Model model) throws IOException, Exception{
    	if(cId == null){
    		 return renderError("重新选择！");
    	}
    	List<CArchivesImageVo> picture = cusGroupImageService.selectPicture(cId);
    	model.addAttribute("listPicture", picture);
		return  "customer/customerPicture";  
    }
    
    /**
     * 上传
     * @return
     */
    @RequestMapping("/uploadPage")
    public String uploadPage() {
        return "customer/customerUpload";
    }
    
    @RequestMapping("/fileUpload")
    @ResponseBody
    public Object fileUpLoad(Integer cId,@RequestParam("fileUpload") MultipartFile fileUpload,
    		HttpServletRequest request, HttpServletResponse response) throws IOException, Exception {   
    	Long a = getUserId();
    	long b = a;
    	int c = (int)b;
    	Integer userId = c;
    	if (cId == null  ) {
    		return renderError("无法在此目录操作!");
		}
		if (fileUpload == null) {
			return renderError("网络异常请稍后再试!");
		}
    	if(fileUpload.isEmpty()){  
    		return renderError("选择文件后上传!");
    	}
    	Boolean bool = saveFiles(fileUpload, request,userId,cId);   //文件上传
    	if(bool){
    		return renderSuccess("添加成功！");
    	}else{
    		return renderError("请确认图片！");
    	}
    }
    
    
    private Boolean saveFiles( MultipartFile myfile, HttpServletRequest request,
			Integer userId,Integer cId)
			throws Exception, IOException {
		String pathRoot = getRootPath();
		String filePath = mkdirs(pathRoot,userId);
		new File(filePath).mkdirs();
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyMMddHHmmss");
		//System.out.println(myfile.getOriginalFilename());
		String Filename = myfile.getOriginalFilename();
		String tempfilePath = filePath + Filename;
		File fileUpload = new File(pathRoot + tempfilePath);
		String fileSuffixName = myfile.getOriginalFilename().substring(          //获得后缀名
		myfile.getOriginalFilename().lastIndexOf("."));
		if(!((fileSuffixName.equals(".JPG")||fileSuffixName.equals(".jpg")||fileSuffixName.equals(".png")||fileSuffixName.equals(".PNG")
				||fileSuffixName.equals(".BMP")||fileSuffixName.equals(".bmp")||fileSuffixName.equals(".wbmp")||fileSuffixName.equals(".jpeg")||
				fileSuffixName.equals(".JPEG")||fileSuffixName.equals(".WBMP")||fileSuffixName.equals(".GIF")||fileSuffixName.equals(".gif")))){
			return false;
		}
		if(fileUpload.exists()){
			String format2 = format.format(date);
			Filename =  format2+"_"+Filename ;
			tempfilePath = filePath + Filename;
			fileUpload = new File(pathRoot + tempfilePath);
		}
		myfile.transferTo(fileUpload);											//=================================上传=========================
		String URL = getbaseUrl(request) + filePath+Filename;				//获得URL
		CArchivesImage archivesImage = new CArchivesImage();
		archivesImage.setCreateId(userId);
		archivesImage.setCreateTime(date);
		archivesImage.setImgPath(URL);
		archivesImage.setCusId(cId);
		File file = new File(URL);
		float imgWidth = ImageTools.getImgWidth(file);           //获得高
		float imgHeight = ImageTools.getImgHeight(file);		//获得宽
		String ratio = imgWidth/imgHeight+"";
		archivesImage.setRatio(ratio);
		cArchivesImageService.insert(archivesImage);
		return true;
	}
    
	private String mkdirs(String pathRoot,Integer userId) {
		Date date = new Date();
		StringBuffer path = new StringBuffer();
		path.append("CusArchives/").append(new SimpleDateFormat("yyyy/MM/dd").format(date))
				.append("/Id_"+userId+"/");
		File f = new File(pathRoot + path.toString());
		if (!f.exists())
			f.mkdirs();
		return path.toString();
	}
    /**
     * 添加页面
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage() {
        return "customer/customerAdd";
    }

    /**
     * 添加
     * @param 
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public Object add(Customer customer) {
        boolean b = customerService.insert(customer);
        if (b) {
            return renderSuccess("添加成功！");
        } else {
            return renderError("添加失败！");
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public Object delete(Long id) {
        boolean b = customerService.deleteById(id);
        if (b) {
            return renderSuccess("删除成功！");
        } else {
            return renderError("删除失败！");
        }
    }

    /**
     * 编辑
     * @param model
     * @param id
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(Model model, Long id) {
        Customer customer = customerService.selectById(id);
        model.addAttribute("customer", customer);
        return "customer/customerEdit";
    }

    /**
     * 编辑
     * @param 
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public Object edit(Customer customer) {
    	Customer customer2 = customerService.selectById(customer.getId());
    	customer2.setAccountNumber(customer.getAccountNumber());
    	customer2.setPhone(customer.getPhone());
    	customer2.setEleNum(customer.getEleNum());
    	customer2.setRateId(customer.getRateId());
    	customer2.setSpecId(customer.getSpecId());
    	customer2.setMeterId(customer.getMeterId());
    	customer2.setName(customer.getName());
        boolean b = customerService.updateById(customer2);
        if (b) {
            return renderSuccess("编辑成功！");
        } else {
            return renderError("编辑失败！");
        }
    }
    
    
    /**
     * 编辑spec
     * @param 
     * @return
     */
    @RequestMapping("/spec")
    @ResponseBody
    public Object spec() {
    	List<EleSpec> eleSpec = eleSpecService.listEleSpec();
    	return eleSpec;
    }
    /**
     * 编辑rate
     * @param 
     * @return
     */
    @RequestMapping("/rate")
    @ResponseBody
    public Object rate() {
    	List<EleRate> listRate = eleRateService.listRate();
    	return listRate;
    }
    
    /**
     * 编辑meter
     * @param 
     * @return
     */
    @RequestMapping("/meter")
    @ResponseBody
    public Object meter() {
    	List<Map<String, Object>> meter = meteringService.listMeter();
    	return meter;
    }
}
